package com.tk.array;

public class Demo06 {
    public static void main(String[] args) {
        //创建一个二维数组 11*11  0:没有棋子   1：黑棋  2：白棋
        int[][] array = new int[5][5];
        array[1][2] = 1;
        array[2][3] = 2;
        System.out.println("输出原始数组");

        for (int[] ints : array) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }
        System.out.println("-----------");
        int sum = 0;
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (array[i][j] != 0) {
                    sum++;
                }
            }
        }
        System.out.println("sum=" + sum);

        //创建一个稀疏数组
        int[][] array1 = new int[sum + 1][3];
        array1[0][0] = 5;
        array1[0][1] = 5;
        array1[0][2] = sum;

        //遍历二维数组，将非 0 的值存入二维数组
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j] != 0) {
                    count++;
                    array1[count][0] = i;
                    array1[count][1] = j;
                    array1[count][2] = array[i][j];
                }
            }
        }
        System.out.println("输出稀疏数组");
        for (int i = 0; i < array1.length; i++) {
            System.out.println(array1[i][0] + "\t" +
                    array1[i][1] + "\t" +
                    array1[i][2]);
        }

        //稀疏数组还原
        System.out.println("还原");
        //1. 读取稀疏数组
        int[][] array2 = new int[array1[0][0]][array1[0][1]];
        //2. 给其中的元素还原值
        for (int i = 1; i < array1.length; i++) {
            array2[array1[i][0]][array1[i][1]] = array1[i][2];
        }
        //打印
        System.out.println("输出还原的数组");
        for (int[] ints : array2) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }
    }
}
